package questions;

import org.junit.jupiter.api.Test;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 *
 */
public class HashSetNotSafe {
    Set<String> set= new HashSet<>();
    //多线程出错的例子
    @Test
    public void testHashSetIssue(){
        for (int i = 0; i <10; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString());
                System.out.println(set);
            },String.valueOf(i)).start();
        }
        while (Thread.activeCount()>2){
            //让出时间片，大家再去抢
            Thread.yield();
        }
        System.out.println(set);
        System.out.println(set.size());
    }
    /**************HashSet多线程不安全的解决方案*********************/

    /**CopyOnWriteArraySet***/
    @Test
    public void testCopyOnWriteSet(){
        Set<String> cpOnWrite = new CopyOnWriteArraySet<>();
        long star= System.currentTimeMillis();
        for (int i = 0; i <1000; i++) {
            new Thread(()->{
                cpOnWrite.add(UUID.randomUUID().toString());
                System.out.println(cpOnWrite);
            },String.valueOf(i)).start();
        }
        while (Thread.activeCount()>2){
            //让出时间片，大家再去抢
            Thread.yield();
        }
        long end = System.currentTimeMillis();
        System.out.println(end-star);
        System.out.println(cpOnWrite);
        System.out.println(cpOnWrite.size());

    }

    /**synchronizedSet***/
    @Test
    public void testSynchronizedSet(){
        Set<String> cpOnWrite = Collections.synchronizedSet(new HashSet<>());
        long star= System.currentTimeMillis();
        for (int i = 0; i <1000; i++) {
            new Thread(()->{
                cpOnWrite.add(UUID.randomUUID().toString());
                System.out.println(cpOnWrite);
            },String.valueOf(i)).start();
        }
        while (Thread.activeCount()>2){
            //让出时间片，大家再去抢
            Thread.yield();
        }
        long end = System.currentTimeMillis();
        System.out.println(end-star);
        System.out.println(cpOnWrite);
        System.out.println(cpOnWrite.size());

    }
}
